import os
import random
import datetime
import yaml


def modify_file_modification_time(root_dir, target_filename=None, allowed_extensions=None):
    print(f"正在处理目录: {root_dir}")
    files_found = False
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            file_ext = os.path.splitext(file)[1].lower().lstrip('.')
            if allowed_extensions and file_ext not in allowed_extensions:
                continue
            file_name_without_ext = os.path.splitext(file)[0]
            if target_filename and target_filename.lower() not in file_name_without_ext.lower():
                continue
            files_found = True
            file_path = os.path.join(root, file)
            try:
                year_str = file_name_without_ext.split(' - ')[-1].strip()
                year = int(year_str)
            except (IndexError, ValueError) as e:
                print(f"从文件名 {file} 中提取年份时出错: {e}")
                continue

            # 生成该年份起 2 年内的任意一个日期
            start_date = datetime.datetime(year, 1, 1)
            end_date = datetime.datetime(year + 2, 12, 31)
            random_days = random.randint(0, (end_date - start_date).days)
            random_date = start_date + datetime.timedelta(days=random_days)

            # 生成随机的小时（范围 7 到 23）、分钟和秒
            random_hour = random.randint(7, 23)
            random_minute = random.randint(0, 59)
            random_second = random.randint(0, 59)

            # 合并日期和随机时间
            random_datetime = random_date.replace(hour=random_hour, minute=random_minute, second=random_second)
            timestamp = random_datetime.timestamp()

            try:
                os.utime(file_path, (timestamp, timestamp))
                print(f"成功修改文件 {file_path} 的修改时间为 {random_datetime.strftime('%Y-%m-%d %H:%M:%S')}")
            except Exception as e:
                print(f"修改文件 {file_path} 的修改时间时出错: {e}")

    if not files_found:
        print(f"在目录 {root_dir} 中未找到符合条件的文件。")


if __name__ == "__main__":
    yml_file_path = os.path.join(os.getcwd(), 'renew_modification_time.yml')
    if os.path.exists(yml_file_path):
        try:
            with open(yml_file_path, 'r', encoding='utf-8') as f:
                config = yaml.safe_load(f)
                root_directory = config.get('search_folder')
                if not root_directory:
                    print("yml 文件中 'search_folder' 节点缺失或为空，按默认逻辑执行。")
                    root_directory = os.path.join(os.getcwd(), 'PDF')
                allowed_extensions = config.get('allowed_extensions', ['pdf', 'epub'])
        except Exception as e:
            print(f"读取 yml 文件时出错: {e}")
            root_directory = os.path.join(os.getcwd(), 'PDF')
            allowed_extensions = ['pdf', 'epub']
    else:
        print(f"指定的 yml 文件 {yml_file_path} 不存在，按默认逻辑执行。")
        root_directory = os.path.join(os.getcwd(), 'PDF')
        allowed_extensions = ['pdf', 'epub']

    print(f"当前要搜索的目录为: {root_directory}")
    target_filename = input("请输入要搜索的文件名（留空则搜索所有文件）: ")

    print(f"当前使用的目录路径: {root_directory}")
    if os.path.exists(root_directory):
        modify_file_modification_time(root_directory, target_filename, allowed_extensions)
    else:
        print(f"指定的目录 {root_directory} 不存在。")